#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
// 仅保留必要头文件，删除重复包含
using namespace std;

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n" << std::endl;
}

// 线程参数改用堆分配，避免栈变量生命周期问题
struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
    std::string serverip;
};

void *recv_message(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    char buffer[1024];
    while (true)
    {
        memset(buffer, 0, sizeof(buffer));
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);

        ssize_t s = recvfrom(td->sockfd, buffer, 1023, 0, (struct sockaddr *)&temp, &len);
        if (s > 0)
        {
            buffer[s] = 0;
            cerr << "[Server/Broadcast] " << buffer << endl; // 明确标注广播消息
        }
    }
}

void *send_message(void *args)
{
    ThreadData *td = static_cast<ThreadData *>(args);
    string message;
    socklen_t len = sizeof(td->server);

    // 修正1：发送欢迎消息（用拼接好的welcome，而非空message）
    std::string welcome = td->serverip;
    welcome += " coming...";
    sendto(td->sockfd, welcome.c_str(), welcome.size(), 0, (struct sockaddr *)&(td->server), len);
    cout << "Send welcome: " << welcome << endl;

    while (true)
    {
        cout << "Please Enter@ ";
        getline(cin, message);

        // 发送用户输入的消息
        sendto(td->sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&(td->server), len);
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1); // 参数错误应异常退出（用1而非0）
    }

    std::string serverip = argv[1];
    uint16_t serverport;
    // 增加端口号合法性校验（避免非数字端口）
    try
    {
        serverport = std::stoi(argv[2]);
    }
    catch (...)
    {
        cerr << "Port must be a number!" << endl;
        exit(1);
    }

    // 修正2：线程参数用new分配（堆内存，生命周期由线程控制）
    ThreadData *td = new ThreadData;
    bzero(&td->server, sizeof(td->server));

    td->server.sin_family = AF_INET;
    td->server.sin_port = htons(serverport);
    // 增加IP合法性校验（避免无效IP）
    if (inet_pton(AF_INET, serverip.c_str(), &td->server.sin_addr) <= 0)
    {
        cerr << "Invalid server IP!" << endl;
        delete td;
        exit(1);
    }

    td->sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td->sockfd < 0)
    {
        perror("socket error");
        delete td;
        return 1;
    }

    td->serverip = serverip;

    pthread_t recvr, sender;
    pthread_create(&recvr, nullptr, recv_message, td);
    pthread_create(&sender, nullptr, send_message, td);

    // 等待线程结束（UDP客户端通常不主动退出，此处阻塞主线程）
    pthread_join(recvr, nullptr);
    pthread_join(sender, nullptr);

    // 释放资源（实际因线程无限循环，此处很少执行）
    close(td->sockfd);
    delete td;
    return 0;
}